package org.lw.springbootlw.auth.controller;

import org.lw.springbootlw.common.response.ApiResponse;
import org.lw.springbootlw.common.response.LoginRequest;
import org.lw.springbootlw.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil; // 用于生成 JWT


    @PostMapping("/login")
    public ResponseEntity<ApiResponse<String>> login(@RequestBody LoginRequest loginRequest) {
        // 参数检查
        if (loginRequest.getUsername() == null || loginRequest.getPassword() == null ||
                loginRequest.getUsername().isEmpty() || loginRequest.getPassword().isEmpty()) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(400, "用户名和密码不能为空", null));
        }

        try {
            System.out.println("Attempting login with username: " + loginRequest.getUsername()+ " and password: " + loginRequest.getPassword());

            // 调用 Spring Security 的认证方法
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
            );

            System.out.println("Authentication successful: " + authentication);

            // 登录成功，生成 JWT
            UserDetails userDetails = userDetailsService.loadUserByUsername(loginRequest.getUsername());
            String jwt = jwtUtil.generateToken(userDetails.getUsername());

            return ResponseEntity.ok().body(new ApiResponse<>(200, "登录成功", jwt)); // 返回 JWT
        } catch (BadCredentialsException e) {
            e.printStackTrace();
            return ResponseEntity.status(401).body(new ApiResponse<>(401, "用户名或密码错误", null));
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常栈
            return ResponseEntity.status(500).body(new ApiResponse<>(500, "服务器错误", null));
        }
    }


}

